import time
import threading

from utils.utils import CONSUL_KEY, consul_client
from model.db.name_mapping import refresh_name_cache


def write_consul_notify():
    """
    每次更新数据库后，写入一个新的值（可使用递增数字或时间戳）
    """
    consul_client.kv.put(CONSUL_KEY, str(int(time.time())))
    print("[CONSUL] Notify key updated.")


# def read_notify_index():
#     """
#     获取当前值和 modifyIndex
#     """
#     index, data = consul_client.kv.get(CONSUL_KEY)
#     return index, data


def start_consul_watch(app):
    '''
    监听 consul_key 触发更新
    '''

    def _watch_key_forever():
        last_index = None
        print(f"[WATCH] Watching Consul key: {CONSUL_KEY}")

        while True:
            try:
                index, data = consul_client.kv.get(CONSUL_KEY, index=last_index, wait='10s')
                if data and data['ModifyIndex'] != last_index:
                    print(f"[WATCH] Detected change on key {CONSUL_KEY}. Refreshing cache.")
                    last_index = data['ModifyIndex']

                    # 触发缓存刷新
                    with app.app_context():
                        refresh_name_cache()
            except Exception as e:
                print("[WATCH ERROR]", e)
                time.sleep(5)

    t = threading.Thread(target=_watch_key_forever, daemon=True)
    # Notice 设置为守护线程 跟随flask项目主线程共同停止
    t.daemon = True
    t.start()
